<template>
  <div class="dataTarget">
    <el-divider content-position="left">
      <i></i>数据来源
    </el-divider>
    <el-form ref="form" :model="dataTarget" label-width="120px" :rules="formRules">
      <el-form-item label="数据库类型" prop="databaseType">
        <el-select v-model="dataTarget.databaseType" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseTypeEvent()">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="database">
        <el-select v-model="dataTarget.database" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseDatabaseEvent()">
          <el-option v-for="item in databaseOptions" :key="item.id" :label="item.datasourceName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <div v-if="mode === 'simpleTable' || mode === 'online'">
        <el-divider content-position="left">
          <i></i>数据库表
        </el-divider>
        <el-form-item label="建表方式" prop="isCreateTable">
          <el-select v-model="dataTarget.isCreateTable" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseBuildTableWayEvent()">
            <el-option v-for="item in buildTableWayOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数据表名" prop="tableName">
          <el-select v-if="dataTarget.isCreateTable === 1" v-model="dataTarget.tableName" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseTableEvent()">
            <el-option v-for="item in tableOptions" :key="item.tableName" :label="item.tableName" :value="item.tableName"></el-option>
          </el-select>
          <el-input v-else v-model="dataTarget.tableName" style="width: 220px"></el-input>
        </el-form-item>
        <el-divider content-position="left">
          <i></i>字段列表
        </el-divider>
        <div class="tableBox">
          <znxd-list v-if="dataTarget.isCreateTable === 1" :column="column" :page="page" :tableData="columnData" :pagination="false" :select="true" :initData="initSelection" @handlePageChange="handlePageChange(page)" @handleGetSelection="handleGetSelection"></znxd-list>
          <znxd-list-modify v-else v-model="dataTarget.selection" :formColumn="selectionFormColumn" :initData="initSelection" mode="addAndDelete"></znxd-list-modify>
        </div>
      </div>
      <div v-else-if="mode === 'multilist'">
        <el-divider content-position="left">
          <i></i>字段列表
        </el-divider>
        <div class="tableBox">
          <znxd-list-modify v-model="dataTarget.multilistData" :formColumn="formColumn" :initData="tablesData"></znxd-list-modify>
        </div>
      </div>
    </el-form>
  </div>
</template>
<script>
import { typeGetDataSource } from "@/api/dataset/database.js";
import { getTables, getColumnsType } from "@/api/dataset/table.js";
import znxdListModify from "../dataFile/listModify";
import { selectDictionaryByType } from "@/api/dict";
export default {
  components: {
    znxdListModify
  },
  data() {
    return {
      dataTarget: {},
      // 数据库类型字典
      typeOptions: [
        // {
        //   label: "mysql",
        //   value: "mysql"
        // },
        // {
        //   label: "oracle",
        //   value: "oracle"
        // },
        // {
        //   label: "sqlserver",
        //   value: "sqlserver"
        // },
        // {
        //   label: "postgresql",
        //   value: "postgresql"
        // },
        // {
        //   label: "dm",
        //   value: "dm"
        // }
      ],
      buildTableWayOptions: [
        {
          label: "选择已有数据表",
          value: 1
        },
        {
          label: "自动创建数据表",
          value: 2
        }
      ],
      databaseOptions: [],
      tableOptions: [],
      page: {
        pageNo: 1, // 当前位于哪页
        pageSize: 8, // 1页显示多少条
        total: 0
      },
      // 单表
      columnData: [],
      // 列表配置
      column: [
        {
          align: "center",
          name: "columnName",
          label: "字段名称"
        },
        {
          align: "center",
          name: "columnMemo",
          label: "字段别名"
        },
        {
          align: "center",
          name: "columnType",
          label: "字段类型"
        },
        {
          align: "center",
          name: "columnLong",
          label: "字段长度"
        }
      ],
      selectionFormColumn: [
        {
          type: "input",
          name: "columnName",
          label: "字段名称"
        },
        {
          type: "input",
          name: "columnMemo",
          label: "字段别名"
        },
        {
          type: "input",
          name: "columnType",
          label: "字段类型"
        },
        {
          type: "input",
          name: "columnLong",
          label: "字段长度"
        },
        {
          type: "select",
          name: "isPrimary",
          label: "是否主键",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        },
        {
          type: "select",
          name: "isAuto",
          label: "是否自增",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        },
        {
          type: "select",
          name: "isNull",
          label: "允许为空",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        }
      ],
      initSelection: [],
      // 多表
      tablesData: [],
      formColumn: [
        // {
        //   name: "tableName",
        //   label: "原表",
        //   type: "label"
        // },
        // {
        //   name: "tableName",
        //   label: "目标表",
        //   type: "label"
        // },
        // {
        //   init: "自动创建",
        //   label: "目标表建立方式",
        //   type: "label"
        // }
      ],
      formRules: {}
    };
  },
  props: {
    initData: Object,
    mode: String,
    dataSource: Object
  },
  watch: {
    dataTarget: {
      deep: true,
      handler: function (val) {
        // console.log("dataTarget", val)
        this.$emit("input", val);
      }
    },
    initData: {
      deep: true,
      handler: async function (obj) {
        // console.log("initData dataTarget", obj);
        if (obj.writerColumns) {
          this.initSelection = [...obj.writerColumns];
        }
        this.dataTarget = {
          databaseType: obj.writerDatasourceType,
          database: obj.writerDatasourceId,
          // tableName: obj.writerTables.length > 0 ? obj.writerTables[0] : "",
          tableName: obj.writerTables,
          selection: obj.writerColumns,
          updataWay: obj.updataWay,
          increColumn: obj.increColumn,
          isCreateTable: obj.isCreateTable === 0 ? "" : obj.isCreateTable
        };

        // 多表
        if (obj.readerTables) {
          this.tablesData = [...obj.readerTables];
        }

        await this.chooseTypeEvent();
        await this.chooseDatabaseEvent(true);
        await this.chooseTableEvent(true);
        this.setRules(); // 调用验证规则重置
        let _this = this;
        setTimeout(function () {
          _this.$refs.form.clearValidate(); // 消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        }, 30);
      }
    },
    dataSource: {
      deep: true,
      handler: function (val) {
        // console.log("dataTarget dataSource", val);
        // this.tablesData = [];
        // this.tablesData = [...val.multilistData];
        if (val.multilistData) {
          let arrData = [];
          val.multilistData.map((x) => {
            let obj = {
              tableName: x,
              updataWay: 0
            };
            arrData.push(obj);
          });

          this.tablesData = arrData;
        }
      }
    }
  },
  methods: {
    chooseTypeEvent() {
      if (!this.dataTarget.databaseType) {
        return;
      }
      let obj = {
        tableType: this.dataTarget.databaseType
      };
      typeGetDataSource(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.databaseOptions = data.content;
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    chooseDatabaseEvent() {
      if (!this.dataTarget.database) {
        return;
      }
      let obj = {
        datasourceId: this.dataTarget.database
      };
      getTables(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.tableOptions = data.content;
          // if (isFirst) {
          //   this.tablesData = [];
          // }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    chooseBuildTableWayEvent() {
      let _this = this;
      switch (_this.dataTarget.isCreateTable) {
        case 1:
          // 选择已有数据表
          this.columnData = [];
          this.initSelection = this.dataSource.selection;
          break;
        case 2:
          console.log("this.dataSource", _this.dataSource);
          // 自动创建数据表
          _this.dataTarget = {
            ..._this.dataTarget,
            tableName: _this.dataSource.tableName,
            selection: _this.dataSource.selection
          };
          _this.columnData = [];
          _this.initSelection = _this.dataSource.multilistData;
          // console.log("自动创建", _this.initSelection);
          break;
        case 3:
          // 手动创建数据表
          this.dataTarget = {
            ...this.dataTarget,
            tableName: "",
            selection: []
          };
          this.columnData = [];
          this.initSelection = [];

          break;
        default:
          break;
      }
      this.setRules(); // 调用验证规则重置
    },
    chooseTableEvent(isFirst) {
      if (!this.dataTarget.tableName) {
        return;
      }
      let obj = {
        datasourceId: this.dataTarget.database,
        tableName: this.dataTarget.tableName
      };
      getColumnsType(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.columnData = data.content;
          this.page.total = data.total;
          // this.handleGetSelection([]) // 重置选择内容
          if (!isFirst) {
            this.initSelection = [];
          }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    handlePageChange(page) {
      this.page = page;
      this.chooseTableEvent();
    },
    handleGetSelection(data) {
      this.dataTarget = {
        ...this.dataTarget,
        selection: data
      };
    },
    setRules() {
      switch (this.mode) {
        case "simpleTable":
          this.formRules = {
            databaseType: [{ required: true, message: "不能为空" }],
            database: [{ required: true, message: "不能为空" }],
            isCreateTable: [{ required: true, message: "不能为空" }],
            tableName: [{ required: true, message: "不能为空" }],
            updataWay: [{ required: true, message: "不能为空" }]
          };
          break;
        case "online":
          this.formRules = {
            databaseType: [{ required: true, message: "不能为空" }],
            database: [{ required: true, message: "不能为空" }],
            isCreateTable: [{ required: true, message: "不能为空" }],
            tableName: [{ required: true, message: "不能为空" }],
            updataWay: [{ required: true, message: "不能为空" }]
          };
          break;
        case "multilist":
          this.formRules = {
            databaseType: [{ required: true, message: "不能为空" }],
            database: [{ required: true, message: "不能为空" }]
          };
          break;
        default:
          break;
      }
    },
    // 校验数据
    validateForm() {
      let flag = true;

      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
          return flag;
        }
      });

      switch (this.mode) {
        case "simpleTable":
          if (
            !this.dataTarget.selection ||
            this.dataTarget.selection.length === 0
          ) {
            flag = false;
            this.$message({
              message: "字段列表不能为空",
              type: "error"
            });
            return flag;
          }
          break;
        default:
          break;
      }

      return flag;
    },
    // import { selectDictionaryByType } from "@/api/dict";
    getDBType() {
      selectDictionaryByType({ type: "dbType" })
        .then((res) => {
          let data = res.data;
          if (data.code === 200) {
            let options = [];
            data.data.map((x) => {
              options.push({ label: x.value, value: x.value });
            });
            this.typeOptions = options;
            // this.initForm();
          } else {
            // this.$message.error(data.msg);
          }
        })
        .catch(() => {
          // this.$message.error("操作失败");
        });
    },
    initForm() {
      this.formColumn = [
        {
          name: "tableName",
          label: "原表",
          type: "label"
        },
        {
          name: "tableName",
          label: "目标表",
          type: "label"
        },
        {
          init: "自动创建",
          label: "目标表建立方式",
          type: "label"
        }
      ];
    }
  },
  mounted() {
    this.getDBType();
    this.initForm();
    if (this.initData.writerColumns) {
      this.initSelection = [...this.initData.writerColumns];
    }
    this.setRules();
  }
};
</script>
<style lang="scss" scoped>
.dataTarget {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
}
</style>
